<template>
    <div class="main-2">
        <div class="consultation-card">
            <div class="question-section">
                <div class="question-text">{{ textInput }}</div>
                <div class="avatars">

                    <img :src="image" alt="User Avatar" class="avatar" v-for="(image, k) in images" :key="k">

                </div>
            </div>

            <div class="doctor-info">

                <img :src="doctor.avatar" alt="Doctor Avatar" class="doctor-avatar">

                <div class="doctor-details">
                    <h3 class="doctor-name">{{ doctor.name }}</h3>
                    <p class="doctor-title">{{ doctor.department }} | {{ doctor.hospital_name }}</p>
                </div>
                <div class="price">
                    <span class="currency">¥</span>{{ doctor.consultation_price }}

                </div>
            </div>

            <div class="service-details">
                <div class="service-item">
                    <h4 class="service-title">优惠方式</h4>
                    <p class="service-value" @click="Couponlist">
                        {{ selectedCoupon ? selectedCoupon.name : '未选择优惠券' }} >
                    </p>
                </div>

                <!-- 如果有优惠券信息，才显示优惠券样式 -->
                <div v-if="selectedCoupon" class="coupon-display">
                    <div class="coupon-left">
                        <span class="discount-amount">
                            {{ selectedCoupon.sale.startsWith('-') ? '￥' + selectedCoupon.sale.replace('-', '') :
                                (selectedCoupon.sale.startsWith('*') ? (parseFloat(selectedCoupon.sale.replace('*', '')) *
                            10) + '折' : '') }}
                        </span>
                    </div>
                    <div class="coupon-right">
                        <div class="coupon-type">{{ selectedCoupon.name }}</div>
                        <div class="coupon-condition">
                            <span class="coupon-start">满{{ selectedCoupon.condition }}可用</span>
                        </div>
                    </div>
                </div>


                <div class="service-item">
                    <h4 class="service-title">权益保障</h4>
                    <p class="service-value">预计3小时内回复，超过24小时自动退款</p>
                </div>

                <div class="service-item public-question">
                    <div class="question-left">
                        <h4 class="service-title">公开问题</h4>
                        <p class="service-value">
                            <span class="highlight">13,842,390</span>
                            人公开问题，帮助更多人
                        </p>
                    </div>
                    <button class="custom-public-button" :class="{ active: isActive }" @click="togglePublic"></button>
                </div>
            </div>

            <div class="agreement">
                <input type="checkbox" v-model="agreed" />
                <span class="agreement-text">
                    我已阅读并同意 <a href="https://ask.dxy.com/index#/find/informed" class="link">《隐私条款及医者职业声明书》</a>
                </span>
            </div>

            <div class="payment-footer">
                <div class="total">
                    <span>合计：</span>
                    <span class="total-price">
                        <span class="currency">¥</span>{{ discountedPrice }}
                    </span>
                    <span class="note">(含2次免费追问)</span>
                </div>
                <button class="pay-button" :disabled="!agreed" @click="showPaymentModal = true">
                    立即支付
                </button>
            </div>
            <!-- Payment Modal -->
            <PaymentModal :show="showPaymentModal" :price="discountedPrice" :onClose="() => showPaymentModal = false"
                :onSuccess="handlePaymentSuccess" />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import PaymentModal from '../components/PaymentModal.vue'

const router = useRouter();

const textInput = ref('');
const images = ref([]);
const doctor = ref({});
const agreed = ref(false);
const showPaymentModal = ref(false);
const selectedCoupon = ref(null); // 存储当前优惠券
const discountedPrice = ref(0); // 计算后的合计价格

// 读取用户输入数据
const TextField = () => {
    const storedData = localStorage.getItem('userInputData');
    if (storedData) {
        try {
            const parsedData = JSON.parse(storedData);
            textInput.value = parsedData.text || '';
            images.value = parsedData.images || [];
        } catch (error) {
            console.error('读取本地存储数据失败:', error);
        }
    }
};

// 读取医生信息
const Doctor = () => {
    const docIdData = localStorage.getItem('doctorId');
    if (docIdData) {
        const doctorId = JSON.parse(docIdData);
        axios.get(`http://127.0.0.1:8000/doctor/docdetail/${doctorId}/`).then((res) => {
            doctor.value = res.data;
            calculateDiscountedPrice(); // 医生信息加载后重新计算价格
        }).catch((err) => {
            console.error('获取医生信息失败:', err);
        });
    }
};

// 支付成功后处理
const handlePaymentSuccess = (orderData) => {
    showPaymentModal.value = false;
    window.location.href = `/order?orderId=${orderData.id}`;
};

// 跳转到优惠券列表
const Couponlist = () => {
    router.push({path: '/coupon', query: { total: doctor.value.consultation_price }});
};

// 按钮状态
const isActive = ref(false);
const togglePublic = () => {
    isActive.value = !isActive.value;
};

// 从本地存储加载优惠券
const loadCoupon = () => {
    
    const couponData = localStorage.getItem('selectedCoupon');
    if (couponData) {
        try {
            selectedCoupon.value = JSON.parse(couponData);
        } catch (error) {
            console.error('优惠券解析失败:', error);
        }
    }
    calculateDiscountedPrice(); // 无论是否选择优惠券都需计算合计价格
};

// 计算合计价格
const calculateDiscountedPrice = () => {
    const price = parseFloat(doctor.value.consultation_price || 0);
    if (selectedCoupon.value) {
        const { sale } = selectedCoupon.value;
        if (sale.startsWith('-')) {
            discountedPrice.value = Math.max(price - parseFloat(sale.slice(1)), 0);
        } else if (sale.startsWith('*')) {
            const discount = parseFloat(sale.slice(1));
            discountedPrice.value = Math.max(price * discount, 0);
        } else {
            discountedPrice.value = price;
        }
    } else {
        discountedPrice.value = price; // 无优惠券时使用原价
    }
    discountedPrice.value = parseFloat(discountedPrice.value.toFixed(2));
};

// 当医生价格改变时重新计算价格
watch(
    () => doctor.value.consultation_price,
    () => {
        calculateDiscountedPrice();
    }
);

// 页面加载时读取本地存储数据
onMounted(() => {
    
    TextField();
    Doctor();
    loadCoupon();
});
</script>


<style scoped>
.main-2 {
    max-width: 800px;
    /* Adjust this value to control the width */
    margin: 0 auto;
    /* Center the container */
    min-height: 100vh;
    background-color: #f7f8fa;
    padding: 20px;
    padding-bottom: 70px;
    position: relative;
}
.consultation-card {
    background: #ffffff;
    border-radius: 12px;
    padding: 20px;
    max-width: 700px;
    margin: 0 auto;
}

.question-section {
    margin-bottom: 24px;
}

.question-text {
    font-size: 16px;
    color: #333;
    margin-bottom: 16px;
}

.avatars {
    
    display: flex;
    /* 设置为水平布局 */
    flex-wrap: nowrap;
    /* 禁止换行 */
    gap: 12px;
    /* 图片之间的间距 */
    overflow-x: auto;
    /* 添加水平滚动条 */
    margin-right: 10px;
    
    
}

.avatar {
    flex-shrink: 0;
    /* 防止图片被压缩 */
    width: 100px;
    height: 100px;
    object-fit: cover;
    border-radius: 4px;
    border: 1px solid #ddd;
    
}

.doctor-info {
    display: flex;
    justify-content: left;
    
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;
}
.doctor-avatar{
    width: 50px;
    height: 50px;
    border-radius: 12px;
}

.doctor-details{
    margin-left: 20px;
}


.doctor-name {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin: 0;
}

.doctor-title {
    font-size: 14px;
    color: #666;
    margin: 4px 0 0;
}

.price {
    font-size: 20px;
    color: #00b578;
    font-weight: 500;
    margin-left: auto;
}

.currency {
    font-size: 0.8em;
}

.service-details {
    padding: 16px 0;
}

.service-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    
}

.public-question {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.question-left {
    flex: 1;
}


.service-title {
    font-size: 14px;
    color: #666;
    font-weight: normal;
    margin: 10px;
}

.service-value {
    font-size: 14px;
    color: #999;
    margin: 0;
    cursor: pointer;
}

.highlight {
    display: inline-flex;
    color: #f7cb06;
    margin-top: 5px;

}

.custom-public-button {
    position: relative;
    width: 50px;
    /* 开关的宽度 */
    height: 25px;
    /* 开关的高度 */
    background-color: #ddd;
    /* 开关的背景颜色 */
    border-radius: 25px;
    /* 圆形边角 */
    border: none;
    cursor: pointer;
    outline: none;
    transition: background-color 0.3s ease;
}

.custom-public-button::after {
    content: '';
    position: absolute;
    top: 3px;
    /* 调整圆点与边框的间距 */
    left: 3px;
    width: 19px;
    /* 圆点的宽度 */
    height: 19px;
    /* 圆点的高度 */
    background-color: #ffffff;
    /* 圆点的颜色 */
    border-radius: 50%;
    /* 圆形 */
    transition: transform 0.3s ease;
    /* 圆点的平移动画 */
}

.custom-public-button.active {
    background-color: #00b578;
    /* 开启状态的背景颜色 */
}

.custom-public-button.active::after {
    transform: translateX(25px);
    /* 圆点平移的距离 */
}


.agreement {
    display: flex;
    align-items: center;
    gap: 8px;
    margin: 20px 0;
}

.checkbox-icon {
    color: #00b578;
    font-size: 14px;
}

.agreement-text {
    font-size: 12px;
    color: #999;
}

.link {
    color: #00b578;
    text-decoration: none;
}

.payment-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 16px;
    border-top: 1px solid #f0f0f0;
}

.total {
    font-size: 16px;
    color: #666;
}

.total-price {
    color: #00b578;
    font-weight: 500;
    margin: 0 4px;
}

.note {
    color: #999;
    font-size: 12px;
}

.pay-button {
    background: #00b578;
    color: white;
    border: none;
    border-radius: 24px;
    padding: 12px 32px;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.2s;
}

.pay-button:hover {
    background: #009e69;
}

.pay-button:disabled {
    background: #ddd;
    cursor: not-allowed;
}

/* 优惠券 */
.coupon-display {
    display: flex;
    background-color: #00b38a;
    border-radius: 8px;
    margin: 16px 0;
    padding: 10px 16px;
    /* 缩小内边距 */
    max-width: 250px;
    /* 设置最大宽度 */
    color: white;
    overflow: hidden;
}

.coupon-left {
    background-color: #69dbb5;
    display: flex;
    align-items: center;
    padding-right: 10px;
    /* 缩小左右间距 */
    border-right: 1px dashed rgba(255, 255, 255, 0.3);
}

.currency {
    font-size: 18px;
    /* 调整字号 */
    margin-right: 4px;
}

.discount-amount {
    font-size: 28px;
    /* 缩小金额字体 */
    font-weight: bold;
}

.coupon-right {
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 10px;
}

.coupon-type {
    font-size: 14px;
    /* 调整文字大小 */
    font-weight: 500;
    margin-bottom: 4px;
}

.coupon-condition {
    font-size: 12px;
    opacity: 0.8;
}
</style>